package com.chris.core.socket.nio.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * 非阻塞异步模式 socket 客户端
 * 苏斌 2022-3-26
 */
public class SockerNioClientUtil {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 端口
     */
    private int port;

    /**
     * 消息断言
     */
    private String breakMark = "\r\n";// \n    \r\n    ~!@#bbq8$%^&*\n;

    /**
     * 客户端通道
     */
    SocketChannel socketChannel;

    private void SockerNioClientUtil(int port) {
        IntSystem(port, "\r\n");
    }

    private void IntSystem(int port, String breakMark) {
        this.port = port;
        this.breakMark = breakMark;

    }

    /**
     * 打开端口
     *
     * @throws IOException
     */
    public void Open() throws IOException, InterruptedException {
        socketChannel = SocketChannel.open();
        //异步方式
        socketChannel.configureBlocking(false);
        InetSocketAddress address = new InetSocketAddress(port);
        boolean isConnect = socketChannel.connect(address);
        if (!isConnect) {
            //因为异步，所以要等待链接完成
            int i = 0;
            while (!socketChannel.finishConnect()) {
                i++;
                Thread.sleep(1000);
                if (i >= 30) {
                    log.error("链接失败");
                    break;
                }

            }

        //链接成功
    }
}


    //#region 发送消息及其命令

    public void SendMsg(String msg) throws IOException {
        synchronized(socketChannel) {
            if (socketChannel == null || !socketChannel.finishConnect()) {
                log.error("客服端不存在,或未连接");
                throw new IOException("客服端不存在,或未连接");
            }

            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
            socketChannel.write(buffer);
        }

    }

    /**
     * 发送文件
     */
    public void SendFile() throws IOException {
        //String fileName, File file
        //if (file==null || !file.isFile() || !file.exists())
        //    return;
        File file = new File("./tip_rev.txt");
        //文件流
        FileInputStream fileInputStream = new FileInputStream(file);
        //文件通道
        FileChannel fileChannel =fileInputStream.getChannel();
        //------------------创建bytefuffer----------------
        ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());
        //------------------------------------------------
        //将文件写入buffer
        fileChannel.read(byteBuffer);
        fileChannel.close();

    }

    //#endregion

}
